package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.GlobalResource;
import com.letv.whatslive.model.GlobalSwitch;
import com.letv.whatslive.model.convert.GlobalResourceConvert;
import com.letv.whatslive.model.convert.GlobalSwitchConvert;
import com.letv.whatslive.model.utils.ObjUtils;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

//2015.11.4

/**
 * 渠道操作DAO
 * Created by shenyue on 2015/11/4.
 */
@Repository
public class GlobalSwitchDAO extends BaseDAO {
    protected String collectionName = "globalswitch";

    private static final Logger logger = LoggerFactory.getLogger(GlobalSwitchDAO.class);

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    public Long saveOrUpdate(GlobalSwitch globalSwitch) {
        DBObject query = new BasicDBObject("_id", globalSwitch.getId());
        DBObject dbo = this.dbCollection.findOne(query);
        if (dbo == null) {
            if(globalSwitch.getId()==null)
                globalSwitch.setId(getAutoIncrementId());
            dbo = GlobalSwitchConvert.castGlobalSwitchToDBObject(globalSwitch);
            if (dbo != null) {
                this.dbCollection.save(dbo);
                return ObjUtils.toLong(dbo.get("_id"));
            }
        } else {
            DBObject update = new BasicDBObject();
            if(StringUtils.isNotBlank(globalSwitch.getSwitchDescribe())){
                update.put("switchDescribe",globalSwitch.getSwitchDescribe());
            }
            if(globalSwitch.getSwitchType()!=null){
                update.put("switchType",globalSwitch.getSwitchType());
            }
            if(globalSwitch.getSpecialType()!=null){
                update.put("specialType",globalSwitch.getSpecialType());
            }
            if(globalSwitch.getSwitchStatus()!=null){
                update.put("switchStatus",globalSwitch.getSwitchStatus());
            }
            this.dbCollection.update(query, new BasicDBObject("$set", update), false, false);
            return globalSwitch.getId();
        }

        return 0L;
    }

    /**
     * 根据查询条件查询所有的渠道列表
     * @param params
     * @param start
     * @param limit
     * @return
     */
    public List<GlobalSwitch> getGlobalSwitchListByParams(Map<String, Object> params, Integer start, Integer limit) {
        List<GlobalSwitch> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).limit(limit);//按照视频类型和创建时间倒序
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                GlobalSwitch globalSwitch = GlobalSwitchConvert.castDBObjectToGlobalSwitch(dbObject);
                result.add(globalSwitch);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据查询条件Map获取查询条件对象
     * @param params
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params){
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if (params.get("_id") != null) {
                query.put("_id", ObjectUtils.toLong(params.get("_id")));
            }
            if (params.get("switchType") != null) {
                query.put("switchType", ObjectUtils.toInteger(params.get("switchType")));
            }
            if (params.get("specialType") != null) {
                query.put("specialType", ObjectUtils.toInteger(params.get("specialType")));
            }
            if (params.get("switchStatus") != null) {
                query.put("switchStatus", ObjectUtils.toInteger(params.get("switchStatus")));
            }
            if (params.get("switchDescribe") != null) {
                query.put("switchDescribe", ObjectUtils.toString(params.get("switchDescribe")));
            }
            if (params.get("appVer") != null) {
                query.put("appVer", ObjectUtils.toString(params.get("appVer")));
            }

        }

        return query;
    }


    /**
     * 根据条件获取相应的渠道列表
     * @param params
     * @return
     */
    public List<GlobalSwitch> getAllGlobalSwitchByParams(Map<String, Object> params){
        List<GlobalSwitch> result = Lists.newArrayList();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBCursor cur = this.dbCollection.find(query);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                GlobalSwitch globalSwitch = GlobalSwitchConvert.castDBObjectToGlobalSwitch(dbObject);
                result.add(globalSwitch);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 根据设备Id获取渠道
     * @param id
     * @return
     */
    public GlobalSwitch getGlobalSwitchById(Long id) {
        BasicDBObject query = new BasicDBObject();
        GlobalSwitch globalSwitch = new GlobalSwitch();
        query.put("_id", id);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            globalSwitch = GlobalSwitchConvert.castDBObjectToGlobalSwitch(dbObject);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return globalSwitch;
    }

    public GlobalSwitch saveGlobalSwitch(GlobalSwitch globalSwitch) {
        try {
            globalSwitch.setId(getAutoIncrementId());
            DBObject dbo = GlobalSwitchConvert.castGlobalSwitchToDBObject(globalSwitch);
            WriteResult wr = this.dbCollection.insert(dbo);
            return globalSwitch;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    public Long countGlobalSwitchByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }

    public void updateGlobalSwitch(GlobalSwitch globalSwitch) {
        DBObject queryCondition = new BasicDBObject();
        queryCondition.put("_id", globalSwitch.getId());
        BasicDBObject setValue = (BasicDBObject)GlobalSwitchConvert.castGlobalSwitchToDBObject(globalSwitch);
        //剔除主键修改
        if (setValue.containsField("_id")) {
            setValue.removeField("_id");
        }
        DBObject values = new BasicDBObject("$set", setValue);
        this.dbCollection.update(queryCondition, values, false, false);
    }

    public long insertGlobalSwitch(GlobalSwitch globalSwitch){
        DBObject obj = GlobalSwitchConvert.castGlobalSwitchToDBObject(globalSwitch);
        return this.insert(obj);
    }

    private BasicDBObject getOrderParams(Map<String, Object> orders) {
        BasicDBObject order = new BasicDBObject();
        if(null != orders &&orders.size()>0){
            for(String key : orders.keySet()){
                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        }else{
            //默认按照id倒序排序
            order.append("_id", -1);
        }
        return order;
    }

    public List<GlobalSwitch> getGlobalSwitchListByParams(Map<String, Object> params, Map<String, Object> orders, Integer start, Integer limit) {

        List<GlobalSwitch> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject order = getOrderParams(orders);
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).sort(order).limit(limit);//按createTime的值倒叙排列
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                GlobalSwitch globalSwitch = GlobalSwitchConvert.castDBObjectToGlobalSwitch(dbObject);
                result.add(globalSwitch);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return result;
    }

    public void deleteGlobalSwitchByParams(Long id){
        BasicDBObject query = new BasicDBObject();
        query.put("_id", id);
        this.dbCollection.remove(query);
    }
}